package com.qf.servlet;

import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.UUID;

/**
 * @author Ypl
 * @version V1.0
 * @Project September-mavens
 * @Package com.qf.servlet
 * @Description:
 * @Date 2022/10/17 11:00
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/admin/storage")
public class AdminStorageController {

    @Autowired
    DtsStorageService dtsStorageService;

    /**
     * 查看对象列表
     */
    @GetMapping("/list")
    public Object list(@RequestParam(value = "page",defaultValue = "1") Integer page,
                       @RequestParam(value = "limit",defaultValue = "20")Integer limit,
                       @RequestParam(value = "sort",defaultValue = "add_time")String sort,
                       @RequestParam(value = "order",defaultValue = "desc") String order,
                       String key,String name ){
        //分页查找
        Map<String,Object> data = dtsStorageService.findByPage(page,limit,sort,order,key,name);

        return ResponseUtil.ok(data);
    }

    /**
     * 添加上传OSS对象,且将上传图片信息添加到数据库
     */
    @PostMapping("/create")
    public  Object insert(MultipartFile file) throws Exception {
        /**
         * 需要一个唯一的文件名 objectName
         */
        //获取文件的类型
        String type = file.getContentType();
        //获取文件的大小
        long size = file.getSize();

        //获取原始文件名带后缀的
        String name = file.getOriginalFilename();
        //获取uuid
        String uuid = UUID.randomUUID().toString();

        String objectName = uuid + name ;

        DtsStorage dtsStorage = dtsStorageService.uploadFile(name,(int)size,type,objectName,file.getBytes());

        return ResponseUtil.ok(dtsStorage);
    }

    /**
     * 对象编辑
     */
    @PostMapping("/update")
    public Object update(@RequestBody DtsStorage dtsStorage){
        //判断是否有上行数据
        if(StringUtils.isEmpty(dtsStorage.getName())){
            return ResponseUtil.fail(-1,"名称不能为空");
        }
        DtsStorage dtsStorage1 = dtsStorageService.update(dtsStorage);
        return ResponseUtil.ok(dtsStorage);

    }

    /**
     * 对象删除
     */
    @PostMapping("/delete")
    public Object delete(@RequestBody DtsStorage dtsStorage){
        dtsStorageService.delete(dtsStorage);
        return ResponseUtil.ok();
    }
}
